<?php

require_once "../includes/db_lib.php";
require_once "../includes/media.php";

try {
    $m = new Media($_POST);
	if ($m->media_type() === "note") {
		$m->url_is($_POST["content"]);
	} else {
		$db_conn = new DBConn();
		$query = "SHOW TABLE STATUS LIKE 'media'";
		$result = $db_conn->query($query);
		$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
		$next_id = $row['Auto_increment'];
		
		$filename = $_FILES["content"]["name"];
  		$fname_arr = explode('.', $filename);
  		$file_ext = $fname_arr[count($fname_arr) - 1];
		$url = $m->media_type()."/".$next_id.'.'.$file_ext;

		$m->url_is($url);
	}
	
	// Save metadata to DB.
    $m->save();
    
    // If save went through, then we can copy the content over if necessary.
    if ($m->media_type() !== "note") {
    	if (file_exists($m->url())) {
    		// TODO: handle error
  		} else {
    		move_uploaded_file($_FILES["content"]["tmp_name"], $m->url());
  		}
    }
} catch (Exception $e) {
	// TODO: handle invalid media
    echo $e;
}

?>